import axios from "axios";
import { GetToken, ClearToken } from "../utils/Token";
const req = axios.create({
  // headers[]=""
  // baseURL: "http://localhost:9060",
  baseURL: "http://47.92.193.251:9060/",
  // timeout: 5000,
  responseEncoding: "utf8",
});

req.interceptors.request.use((confing) => {
  // console.log(GetToken());
  confing.headers['token'] = GetToken();
  if (confing.method == "post") {
    confing.headers['content-type'] = "application/json";
  } else if (confing.method == "put") {
    confing.headers['content-type'] = "multipart/form-data";
    // onUploadProgress: function (progressEvent) {
    //   // 处理原生进度事件
    // },
  }

  // confing.headers.token = GetToken();
  // console.log(confing);
  return confing;
});

req.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // console.log(error);
    let one = {
      code: 200,
      message: 200,

    }
    if (!error.response) {
      one.code = 20062
      one.message = "网络连接异常"
      return one
    }
    if (error.response.status == 500) {
      one.code = error.response.status
      one.message = error.message
      return one
    } else if (error.response.status == 401) {
      ClearToken()
      one.code = error.response.status
      one.message = error.message
      window.location.href = window.location.href;
      // window.history.back(-1);
      return one
    }
  }
);

const Axios = (url, method = "POST", data) => {

  const res = req({
    url: url,
    data: data,
    method: method,
    // 获取上传时候的上传进度
    onUploadProgress: function (progressEvent) {
      // 处理原生进度事件

      // let progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
      // console.log(progress);

    },
    // onDownloadProgress: function (progressEvent) {
    //   // 处理原生进度事件
    //   console.log(progressEvent);

    // },

    // headers: {
    //   "token": GetToken(),
    //   "Content-Type": "application/x-www-form-urlencoded"
    // }
  });
  return res;
};

// class Axios {
//   static req = axios.create({
//     // headers[]=""
//     baseURL: "http://localhost:9020/Chat/",
//     // timeout: 5000,
//     responseEncoding: "utf8",
//   });

//   static init(url: string, data?: object, method = "POST") {
//     this.req.interceptors.request.use((confing: any) => {
//       console.log(confing);
//       return confing;
//     });
//     this.req.interceptors.response.use(
//       (response: any) => {
//         console.log(response);

//         // const res = JSON.parse(JSON.stringify(response.data));
//         return response;
//       },
//       (error: any) => {
//         console.log(error);

//         message.error(error.message);
//       }
//     );
//     const res = this.req({
//       url: url,
//       data: data,
//       method: method,
//     });
//     return res;
//   }
// }

export default Axios;
